<template>
    <el-row class="serverCpuLoad">
        <el-col :span="24" class="cpuLoadLine-box">
            <div id="CpuLoad" ref="CpuLoad" class="serCpuLine"></div>
        </el-col>
        <el-col :span="24" class="cpuLoadText-box">
            <span class="CPUtextImformation">CPU 使用率：{{this.cpuUsage? this.cpuUsage: '0'}}&nbsp;%</span>
        </el-col>
    </el-row>
</template>>

<script>
import { fetchData } from '@/api/index.js';
import bus from 'common/bus.js';

export default {
    data() {
        return {
            postData: {
                opera: 'ospanlinfo',
                curPage: 1,
                pageSize: 20,
                sort: {
                    sortColumn: '',
                    sortOrders: ''
                },
                filtersType: 'fuzzyquery',
                filters: {
                    "monid": "",
                },
            },
            xData: '',
            yData: '',
            cpuUsage: '',
            cpuData : this.cpuDataTest(),
            CpuLoad: {},
            EChartsOption: {
                animationDuration: 100,
                animationEasingUpdate: 'quinticInOut',
                tooltip: {
                    trigger: 'axis',
                },
                grid: {
                    top: '9%',
                    // left: '0%',
                    height: '88%',
                    width: '83%',
                    // containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    splitLine: {
                        show: false,
                        lineStyle: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLable:{
                        show: false
                    },
                    data: this.testData(),
                    axisLine: {color:'rgb(29, 140, 248)',lineStyle:{color:'rgb(29, 140, 248)'}},
                },
                yAxis: {
                    type: 'value',
                    min: 0,
                    max: 100,
                    splitNumber: 5,
                    boundaryGap: ['5%', '5%'],
                    splitLine: {
                        show: true,
                        lineStyle: {
                            opacity: 0.3,
                            type: 'dotted',
                            // color: 'rgb(145, 199, 174)',
                            color: 'rgb(29, 140, 248)',
                        }
                    },
                    axisLine: {color:'rgb(29, 140, 248)',lineStyle:{color:'rgb(29, 140, 248)'}},
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        margin: 4,
                        formatter: function (value, index) {
                            return value + '%';
                        }
                    }
                },
                series: [{
                    name: 'CPU使用率',
                    data: this.cpuData,
                    type: 'line',
                    color: 'rgb(194, 131, 213)',
                    showSymbol: false,
                    areaStyle: {
                        opacity: 0.2
                    }
                }]
            },
            timerName: 'CpuLoad',
            timerEventName: 'timerCpuLoad',  
            timerInterval: 1000 * 30,
            cpuLastSN: '0',
            updateFlag: false,
            getNum: 30
        }
    },
    created() {
        bus.$on('selectedMonIDMysql', msg => {
            this.selectedMonID = msg;
            this.postData.filters.monid = this.selectedMonID.selectedOSMonID;
            this.initGetData();
        }); 
        
        bus.$emit('timerNewTodo', {
            name: this.timerName,
            eventName: this.timerEventName,
            interval: this.timerInterval,
            intervalNow: 0
        });

        bus.$on(this.timerEventName, msg => {
            if (msg.isGetData) {

                this.getData();
            }
        });
    },
    mounted() {
        this.CpuLoad = this.$echarts.init(this.$refs.CpuLoad);
        this.drawCPULine();
        window.onresize= () =>{
            let myEchart = this.$echarts.init(this.$refs.CpuLoad);
            myEchart.resize();
        }
    },
    computed: {

    },
    methods: {
        initGetData(){
            this.CpuLoad.showLoading({
                text: '加载中...',
                color: '#c23531',
                textColor: '#fff',
                maskColor: 'rgba(2, 16, 51, 0.8)',
                zlevel: 0,
                fontSize: 12,
                showSpinner: true,
                spinnerRadius: 10,
                lineWidth: 5
            });

            let _postData = {
                opera: 'CpuUsageLine',
                filters: {
                    "monid": this.postData.filters.monid,
                    "pointNum": this.getNum
                },
            };

            fetchData({
                postData : JSON.stringify(_postData)
            }).then((res) => {
                let _cpuNum = [];
                let _xAxisData = [];
                
                if (res.dataTotal > 0) {
                    res.data.forEach(element => {
                        
                        _cpuNum.push(Number((100 - element.CPU_IDLE).toFixed(1)));
                        _xAxisData.push(element.RECORD_TIME);
                    });
                    
                    this.cpuLastSN = [...res.data].pop().SN;
                    this.cpuUsage = Number((100 - [...res.data].pop().CPU_IDLE).toFixed(1));
                }
                
                this.cpuData = _cpuNum;
                this.EChartsOption.xAxis.data = _xAxisData;

                this.CpuLoad.setOption({
                    xAxis: {
                        data: _xAxisData
                    },
                    series: {
                        data: _cpuNum
                    }
                });

                this.CpuLoad.hideLoading();
            });
        },
        getData(){
            let _postData = {
                opera: 'CpuUsageLine',
                filters: {
                    "monid": this.postData.filters.monid,
                    "pointNum":"1"
                },
            };

            fetchData({
                postData : JSON.stringify(_postData)
            }).then((res) => {
                if (res.dataTotal <= 0) {
                    this.xData = '';
                    this.yData = '';
                    this.cpuUsage = '';
                } else if ([...res.data].pop().SN != this.cpuLastSN) {
                    this.cpuLastSN = [...res.data].pop().SN;
                    this.xData = res.data[0].RECORD_TIME.replace(/\s+/g,"\n");
                    this.yData = (100 - res.data[0].CPU_IDLE).toFixed(1);
                    this.cpuUsage = this.yData;

                    // this.updateFlag = true;
                    this.cpuData.shift();
                    this.cpuData.push(this.yData);
                    this.EChartsOption.xAxis.data.shift();
                    this.EChartsOption.xAxis.data.push(this.xData);
                    this.CpuLoad.setOption({
                        xAxis: {
                            data: this.EChartsOption.xAxis.data
                        },
                        series: {
                            data: this.cpuData
                        }
                    });
                }
            });
        },
        drawCPULine(){
            this.CpuLoad.setOption(this.EChartsOption);
        },
        testData() {
            let _arr = [];
            for (let i = 0; i < this.getNum; i++) {
                _arr.push('');
            }
            
            return _arr;
        },
        cpuDataTest() {
            let _arr = new Array(this.getNum);
            
            return _arr;
        }
    },
    beforeDestroy() {
        bus.$emit('timerNewTodo', {
            name: this.timerName
        });
        
        this.CpuLoad.dispose();
    },
    // watch:{
    //     'EChartsOption': {
    //         handler: function () {
    //             this.drawCPULine();
    //         },
    //         deep: true
    //     }
    // }
}
</script>

<style scoped>
.serverCpuLoad{
	height: calc(100% - 22px - 8px);
	margin-bottom: 0 !important;
	text-align: left;
}
.cpuLoadLine-box{
    height: calc(75% - 5px);
}
.serCpuLine{
    height: calc(100% - 1px);
    
}
.cpuLoadText-box{
    height: calc(100% - 75% + 5px);
    text-align: center;
    margin-top: 1%;
    overflow: hidden;
}
.CPUtextImformation{
    color: seashell;
    font-size: x-large;
}
</style>